package cn.tedu.powerfulfitness.service.impl;

import cn.tedu.powerfulfitness.ex.ServiceException;
import cn.tedu.powerfulfitness.mapper.CoachMapper;
import cn.tedu.powerfulfitness.pojo.dto.CoachAddNewDTO;
import cn.tedu.powerfulfitness.pojo.dto.CoachUpdateDTO;
import cn.tedu.powerfulfitness.pojo.entity.Coach;
import cn.tedu.powerfulfitness.pojo.vo.CoachListItemVO;
import cn.tedu.powerfulfitness.pojo.vo.CoachStandardVO;
import cn.tedu.powerfulfitness.service.ICoachService;
import cn.tedu.powerfulfitness.web.ServiceCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class CoachServiceImpl implements ICoachService {

    @Autowired
    private CoachMapper coachMapper;

    @Value("${imagePath}")
    String dirPath;


    @Override
    public void addNew(CoachAddNewDTO coachAddNewDTO) {
        //从参数对象中获取教练年龄
        Integer age = coachAddNewDTO.getAge();
        String age1 = String.valueOf(age);
        //判断输入的年龄是否正确
        if (!age1.matches("[0-9]{1}|[1-9]{1}[0-9]{1}")){
            //抛异常
            String message = "添加教练失败，年龄输入格式有误!";
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,message);
        }

        //从参数对象中获取教练教龄
        Integer seniority = coachAddNewDTO.getSeniority();
        String seniority1 = String.valueOf(seniority);
        //判断输入的教龄是否正确
        if (!seniority1.matches("[0-9]{1}|[1-9]{1}[0-9]{1}")){
            //抛异常
            String message = "添加教练失败，教龄输入格式有误!";
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,message);
        }

        //从参数对象中获取教练手机号
        Long tel = coachAddNewDTO.getTel();
        // 调用coachMapper的int countByTel(Long tel)根据手机号执行统计
        int countByTel = coachMapper.countByTel(tel);
        if (countByTel > 0) {
            // 是：抛出异常
            String message = "添加教练失败，手机号已经被占用！";
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        String tel1 = String.valueOf(tel);
        //判断输入的手机号是否是"1"开头的11位数字
        if (!tel1.matches("[1]{1}[0-9]{10}")){
            //抛异常
            String message = "添加教练失败，手机号输入格式有误!";
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,message);
        }

        // 创建coach对象
        Coach coach = new Coach();
        // 调用BeanUtils.copyProperties()将参数对象的属性值复制到Album对象中
        BeanUtils.copyProperties(coachAddNewDTO, coach);
        // 调用albumMapper的int insert(Album album)方法将相册数据插入到数据库
        int rows = coachMapper.insert(coach);
        if (rows != 1){
            String message = "添加教练失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void deleteById(Long id) {
        CoachStandardVO queryResult = coachMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "删除教练失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        int rows = coachMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除教练失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }

    }

    @Override
    public void updateInfoById(Long id, CoachUpdateDTO coachUpdateDTO) {
        CoachStandardVO queryResult = coachMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "修改教练详情失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        //从参数对象中获取教练年龄
        String age = String.valueOf(coachUpdateDTO.getAge());
        //判断输入的年龄是否正确
        if (!age.matches("[0-9]{1}|[1-9]{1}[0-9]{1}")){
            //抛异常
            String message = "修改教练详情失败，教龄输入格式有误!";
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,message);
        }

        //从参数对象中获取教练教龄
        String seniority = String.valueOf(coachUpdateDTO.getSeniority());
        //判断输入的教龄是否正确
        if (!seniority.matches("[0-9]{1}|[1-9]{1}[0-9]{1}")){
            //抛异常
            String message = "修改教练详情失败，教龄输入格式有误!";
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,message);
        }

        //从参数对象中获取教练手机号
        Long tel = coachUpdateDTO.getTel();
        // 调用coachMapper的int countByTel(Long tel)根据手机号执行统计
        int countByTel = coachMapper.countByTelAndNotId(id,tel);
        if (countByTel > 0) {
            // 是：抛出异常
            String message = "修改教练详情失败，手机号已经被占用！";
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        String tel1 = String.valueOf(tel);
        //判断输入的手机号是否是"1"开头的11位数字
        if (!tel1.matches("[1]{1}[0-9]{10}")){
            //抛异常
            String message = "修改教练详情失败，手机号输入格式有误!";
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,message);
        }

        Coach coach = new Coach();
        BeanUtils.copyProperties(coachUpdateDTO, coach);
        coach.setId(id);
        int rows = coachMapper.update(coach);
        if (rows != 1) {
            String message = "修改相册详情失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }


    }

    @Override
    public CoachStandardVO getStandardById(Long id) {
        CoachStandardVO queryResult = coachMapper.getStandardById(id);
        if (queryResult == null){
            String message = "获取相册详情失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public List<CoachListItemVO> list() {
        List<CoachListItemVO> list = coachMapper.list();
        return list;
    }

    // 上传图片
    @Override
    public String uploadIcon(MultipartFile multipartFile){
        String fileName = multipartFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        //日期路径
        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        File dirFile = new File(dirPath+datePath);
        //判断文件夹不存在 则创建
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //保存文件到指定文件夹  异常抛出
        try {
            multipartFile.transferTo(new File(dirPath+datePath+fileName));
        } catch (IOException e) {
            String message = "图片上传错误";
            throw new ServiceException(ServiceCode.ERR_UPLOAD, message);
        }
        return datePath+fileName;
    }

    //删除图片
    @Override
    public void removeIcon(String url) {
        new File(dirPath + url).delete();
    }

}
